import { getPermissionList } from "@/api/permission";
import { Permission } from "@/typings/api/permission";
import { Select, SelectProps } from "antd";
import { FC, useEffect, useState } from "react";

interface PermissionSelectProps extends SelectProps {
    value?: string[];
}
const PermissionSelect: FC<PermissionSelectProps> = ({ value, onChange, ...props }) => {
    const [permissionList, setPermissionList] = useState<Permission[]>([]);
    const fetchPermissionList = async () => {
        // prettier-ignore
        const { data } = await getPermissionList();
        const list: Permission[] = [];
        const loop = (permissionList: Permission[] = []) => {
            permissionList.forEach(item => {
                list.push({ ...item, children: [] });
                loop(item.children as Permission[]);
            });
        };
        loop(data);
        setPermissionList(list);
    };
    useEffect(() => {
        fetchPermissionList();
    }, []);
    const [innerValue, setInnerValue] = useState<string[]>([]);
    useEffect(() => {
        setInnerValue(value || []);
    }, [value]);
    return (
        <Select
            {...props}
            value={innerValue}
            onChange={(val, option) => {
                setInnerValue(val);
                onChange?.(val, option);
            }}
            showSearch
        >
            {permissionList.map(item => (
                <Select.Option key={item._id} value={item.key}>
                    {item.key}
                </Select.Option>
            ))}
        </Select>
    );
};

export default PermissionSelect;
